// pages/message/index.js
const app = getApp();
const db = wx.cloud.database();
const _ = db.command;
import {formatTime} from '../../utils/util';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    messageList: [],
    userList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad:async function (options) {
    
  },
  async getData(){
    let {result} = await wx.cloud.callFunction({
      name: 'getMessageList'
    });
    let {_id} = wx.getStorageSync('userInfo');
    let {messageList} = result;
    // console.log(messageList);
    let groupidList = [];
    messageList.forEach(item=>{
      console.log(item);
      if(groupidList.findIndex(item1=>item1.groupId===item.groupId)===-1&&item.id.includes(_id)){
        groupidList.push({
          groupId:  item.groupId,
          uid: item.id.replace(_id, ""),
          id:item.id,
          Lcontent: item.textContent,
          sendTime: item.sendTime
        });
      }
    });
    let userList = [];
    groupidList.forEach(async item=>{
      let info = await db.collection('user').doc(item.uid).get();
      info.data.groupId = item.groupId;
      info.data.id = item.id;
      info.data.Lcontent = item.Lcontent;
      info.data.sendTime = item.sendTime;
      info.data.time = formatTime(Date.parse(item.sendTime)/1000);
      userList.push(info.data)
      wx.setStorageSync('userList', userList.sort(function(a,b){
        return new Date(a.sendTime).getTime()<new Date(b.sendTime).getTime()
      }));
      await this.setData({
        messageList,
        userList:userList
      });
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady:async function () {
    let userList = wx.getStorageSync('userList');
    let groupIDs = userList.map(item=>item.groupId);
    db.collection('chatroom').where({
      groupId: _.in(groupIDs)
    }).watch({
      onChange: (snapshot)=>{
        if(snapshot.type !== 'init'){
          console.log(snapshot);
          let info = snapshot.docs[snapshot.docs.length - 1 ];
          wx.showToast({
            title: `${info.nickName}发了信息`,
            icon: 'none'
          })
        }else{
          console.log('初始化');
        }
      },
      onError: (err)=>{
        console.log(err);
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {
    this.getData()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showLoading({
      title: '加载中',
      mask: true,
      success: ()=>{
        this.setData({
          userList:[]
        });
        setTimeout(()=>{
          this.getData();
          wx.hideLoading();
        },1000);
      }
    })
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})